﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace StarryEdge.Menu.Device.Helper
{
    public class NetworkAdapterHelper
    {
        public static List<NetworkInterface> GetAllNetworkAdapters()
        {

            IEnumerable<NetworkInterface> adapters = NetworkInterface.GetAllNetworkInterfaces();
            List<NetworkInterface> list = new List<NetworkInterface>();
            foreach (NetworkInterface adapter in adapters)
            {
                if (adapter.OperationalStatus == OperationalStatus.Up && !adapter.Name.Contains("Loopback"))
                {
                    list.Add(adapter);
                }
            }
            return list;
        }

        public static bool SetIPAddress(string[] ip, string[] submask, string networkInterfaceID)
        {
            if (ip == null || submask == null) { return false; }
            ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = wmi.GetInstances();
            ManagementBaseObject inPar;
            ManagementBaseObject outPar;
            string? str;
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"] || networkInterfaceID != mo["SettingID"].ToString()) { continue; }
                string? caption = mo["Caption"].ToString();
                inPar = mo.GetMethodParameters("EnableStatic");
                inPar["IPAddress"] = ip;
                inPar["SubnetMask"] = submask;
                outPar = mo.InvokeMethod("EnableStatic", inPar, null);
                str = outPar["returnvalue"].ToString();
                return (str == "0" || str == "1") ? true : false;
            }
            return false;
        }
    }
}
